package com.glowdayz.glowmee.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import com.glowdayz.common.DBHandler;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.PageHandler;
import com.glowdayz.common.MultipartBox.FileInfo;
import com.glowdayz.glowmee.cmd.PouchBannerCMD;

public class PouchBannerDAO {
	
	static Logger logger = Logger.getLogger(PouchBannerDAO.class);
	
	private static PouchBannerDAO instance = null;
	
	DBHandler db = null;
	
	public static PouchBannerDAO getInstance() {
		if (instance == null) {
			instance = new PouchBannerDAO();
		}
		return instance;
	}
	
	public PouchBannerDAO() {
		db = DBHandler.getInstance();
	}
	
	/**
	 * 파우치배너 추가
	 * @param cmd
	 * @return int
	 */
	public int insertPouchBanner(PouchBannerCMD cmd) throws Exception {
		logger.debug("[insertPouchBanner] ---------- Method Start ----------");
		logger.debug("[insertPouchBanner][PARAM] BrandBannerCMD cmd=" + cmd.toString());
		
		int result = 0;
		
		PreparedStatement pstmt = null;
		
		String sql = "INSERT INTO pouchbanner("
				+ "idPouch, bannerTitle, bannerLinkType, bannerLinkCode, sortKey, isDisplay, create_date"
				+ ") VALUES (?, ?, ?, ?, ?, 1, ?)";
		
		pstmt = db.getPrepareStatement(sql);
		
		DBHandler.getInstance().beginTrans();
		try {
			pstmt.setInt(1, cmd.getIdPouch());
			pstmt.setString(2, cmd.getBannerTitle());
			pstmt.setInt(3, cmd.getBannerLinkType());
			pstmt.setString(4, cmd.getBannerLinkCode());
			pstmt.setInt(5, cmd.getSortKey());
			pstmt.setString(6, DateTime.getInstance().getNowDateTimeString());
			result = pstmt.executeUpdate();
			
			if (result > 0) {
				// 자동증가 일련변호 조회
				ResultSet rs = pstmt.getGeneratedKeys();
				if (rs.next()) {
					result = rs.getInt(1);
				}
				rs.close();
				rs = null;
			}
			
			pstmt.close();
			pstmt = null;
			
			if (cmd.getImage() != null) {
				
				String fileSql = "INSERT INTO attachefile ("
						+ "tableName, tableKey, fileOrgName, fileSaveName, fileDir, fileSize, fileType, isDisplay, create_date, isUser"
						+ ") VALUES ('pouchbanner', ?, ?, ?, ?, ?, ?, 1, ?, 0)";
				
				int fileResult = 0;
				
				FileInfo item = cmd.getImage();
				
				pstmt = db.getPrepareStatement(fileSql);
				pstmt.setInt(1, result);
				pstmt.setString(2, item.getFileOrgName());
				pstmt.setString(3, item.getFileSaveName());
				pstmt.setString(4, item.getFileDir());
				pstmt.setLong(5, item.getFileSize());
				pstmt.setString(6, item.getFileType());
				pstmt.setString(7, DateTime.getInstance().getNowDateTimeString());
				
				fileResult = pstmt.executeUpdate();
				
				if (fileResult > 0) {
					// 자동증가 일련변호 조회
					ResultSet rs = pstmt.getGeneratedKeys();
					if (rs.next()) {
						fileResult = rs.getInt(1);
					}
					rs.close();
					rs = null;
				} else {
					// 모든 데이터 저장 취소
					pstmt.close();
					pstmt = null;
					DBHandler.getInstance().rollback();
					return -1;
				}
				
				pstmt.close();
				pstmt = null;
					
				
				String update = "UPDATE pouchbanner "
						+ "SET bannerImg=? "
						+ "WHERE idPouchBanner=?";
				pstmt = db.getPrepareStatement(update);
				pstmt.setInt(1, fileResult);
				pstmt.setInt(2, result);
				result = pstmt.executeUpdate();
				pstmt.close();
				pstmt = null;
			}
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[insertPouchBanner] " + e.getLocalizedMessage());
			logger.error("[insertPouchBanner] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[insertPouchBanner][RETURN] result=" + result);
		logger.debug("[insertPouchBanner] ---------- Method End ----------");
		
		return result;
	}
	
	/**
	 * 파우치 배너 수정
	 * @param cmd
	 * @return int
	 * @throws SQLException 
	 */
	public int updatePouchBanner(PouchBannerCMD cmd) throws SQLException {
		logger.debug("[updatePouchBanner] ---------- Method Start ----------");
		logger.debug("[updatePouchBanner][PARAM] PouchBannerCMD cmd=" + cmd.toString());
		
		int result = 0;
		
		DBHandler.getInstance().beginTrans();
		PreparedStatement pstmt = null;
		
		// (3) 게시물 정보 갱신
		String sql = "UPDATE pouchbanner "
				+ "SET bannerTitle=?, bannerLinkType=?, bannerLinkCode=?, sortKey=?, isDisplay=?, modified_date=? "
				+ "WHERE idPouchBanner=?";
		pstmt = db.getPrepareStatement(sql);
		
		try {
			pstmt.setString(1, cmd.getBannerTitle());
			pstmt.setInt(2, cmd.getBannerLinkType());
			pstmt.setString(3, cmd.getBannerLinkCode());
			pstmt.setInt(4, cmd.getSortKey());
			pstmt.setInt(5, cmd.getIsDisplay());
			pstmt.setString(6, DateTime.getInstance().getNowDateTimeString());
			pstmt.setInt(7, cmd.getIdPouchBanner());
			
			result = pstmt.executeUpdate();
			
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[updatePouchBanner] " + e.getLocalizedMessage());
			logger.error("[updatePouchBanner] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[updatePouchBanner][RETURN] result=" + result);
		logger.debug("[updatePouchBanner] ---------- Method End ----------");
		
		return result;
	}
	
	/**
	 * 파우치배너 리스트
	 * @param page
	 * @param count
	 * @param idBrand
	 * @return ArrayList<PouchBannerCMD>
	 */
	public ArrayList<PouchBannerCMD> getPouchBannerList(int page, int count, String where) throws Exception {
		logger.debug("[getPouchBannerList] ---------- Method Start ----------");
		logger.debug("[getPouchBannerList][PARAM] page=" + page);
		logger.debug("[getPouchBannerList][PARAM] count=" + count);
		logger.debug("[getPouchBannerList][PARAM] where=" + where);
		
		ArrayList<PouchBannerCMD> result = null;
		int cnt = db.getCount("pouchbanner b, pouch p", "*", where);
		
		if (count == -1) {
			count = cnt;
		}
		
		String sql = "SELECT b.idPouchBanner, b.bannerTitle, b.bannerLinkType, b.bannerLinkCode, b.bannerImg, b.sortKey, b.isDisplay "
				+ "FROM pouchbanner b, pouch p "
				+ "WHERE " + where + " "
				+ "ORDER BY b.sortKey, b.create_date DESC "
				+ "LIMIT ?, ?";
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(sql);
		
		if (cnt == 0) {
			PageHandler.getInstance(page, cnt);
		} else {
			// 페이징 처리 --> 한 페이지에 count개씩, 페이지번호는 10개 출력
			PageHandler.getInstance(page, cnt, count, 10);
		}
		
		try {
			pstmt.setInt(1, PageHandler.getInstance().getStartRec());
			pstmt.setInt(2, PageHandler.getInstance().getPageArticleCount());
			ResultSet rs = pstmt.executeQuery();
			
			if (rs != null) {
				
				// SQL문장에 이상이 없을 경우에만 list 객체를 할당한다.
				// 이 객체가 null이라면 SQL실행에 실패한 경우이다.
				// 객체가 생성되지만, add()가 실행되지 않아서, size()값이 0이라면
				// 조건에 맞는 데이터가 없는 경우이다.
				result = new ArrayList<PouchBannerCMD>();
				
				while(rs.next()) {
					int idPouchBanner = rs.getInt(1);
					String bannerTitle = rs.getString(2);
					int bannerLinkType = rs.getInt(3);
					String bannerLinkCode = rs.getString(4);
					int bannerImg = rs.getInt(5);
					int sortKey = rs.getInt(6);
					int isDisplay = rs.getInt(7);
					
					FileInfo image = this.getImage(idPouchBanner);
					PouchBannerCMD item = new PouchBannerCMD(idPouchBanner, bannerTitle, bannerLinkType, bannerLinkCode, bannerImg, sortKey, isDisplay, image);
					result.add(item);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error("[getPouchBannerList] " + e.getLocalizedMessage());
			logger.error("[getPouchBannerList] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result != null) {
			logger.debug("[getPouchBannerList][RETURN] result_count=" + result.size());
		}
		logger.debug("[getPouchBannerList] ---------- Method End ----------");
		
		return result;
	}
	
	public FileInfo getImage(int idx) throws SQLException {
		String fileSql = "SELECT fileOrgName, idAttacheFile, fileSaveName, fileDir, fileSize, fileType "
				+ "FROM attachefile "
				+ "WHERE tableName='pouchbanner' AND tableKey=?";
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(fileSql);
		FileInfo info = null;
		
		try {
			pstmt.setInt(1, idx);
			ResultSet rs = pstmt.executeQuery();
			if (rs != null) {
				while(rs.next()) {
					String fileOrgName = rs.getString(1);
					int idAttacheFile = rs.getInt(2);
					String fileSaveName = rs.getString(3);
					String fileDir = rs.getString(4);
					int fileSize = rs.getInt(5);
					String fileType = rs.getString(6);
					
					info = new FileInfo("", idAttacheFile, fileOrgName, fileSaveName, fileDir, fileSize, fileType);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error(e.getLocalizedMessage());
			logger.error(e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		return info;
	}
	
}
